C++ Date & Time

    In C++ we do not have a specific Data type to represent the time and date so we inherit the structure and functions from the C programming language. To use data and time in C++ we have a library which can represent data and time in integer format, and to access this library we need to include the <time.h> header file in our C++ program.

    <time.h> Functions

    In general <time.h> header file provide us four different versions of time types which are clock_t, time_t, size_t, and tm.

    Functions Descriptions
    time_t time(time_t *time); This function returns the current time of your system in number of seconds since January 1, 1970.
    char *ctime(const time_t *time); This function return a pointer to a string in the form of day month hours:minutes:seconds
    struct tm *localtime(const time_t *time); This function return a pointer to the tm structure which represent the local time.
    clock_t clock(void); It returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available.
    char * asctime ( const struct tm * time ); It return a string pointer which contain the time information in the form of day month date hours:minutes:seconds year\n\0
    struct tm *gmtime(const time_t *time); It returns a tm structure pointer.
    time_t mktime(struct tm *time); This returns the calendar-time equivalent of the time found in the structure pointed to by time
    double difftime ( time_t time2, time_t time1 ); It is used to find the time difference between two point of times.
    size_t strftime(); This function ca format data and time in a specific format.

    Print the Current data and time:

    #include <iostream>
    #include <time.h> // include the time header file
    
    using namespace std;
    int main()  
        {
    
       time_t current = time(0); // time_t is the time data type
       char* date_and_time = ctime(&current);                           // it will convert the time into string
       cout << "The Current data and time is: " << date_and_time << endl;
    
       }

    Output

    The Current data and time is: Thu Jan 14 19:53:31 2020

    Quick Summary

    • C++ use the C library to access the data and time.
    • To use the time library, we need to include the <time.h> in our C++ program.

    People are also reading: